package mya.mes.mdc.logic.mqtt;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import mya.mes.mdc.local.alarm.MdcAlarmResult;
import mya.mes.mdc.local.json.AbstractJsonSerializer;
import mya.mes.mdc.model.alarm.MdcAlarm;
import mya.mes.mdc.share.plc.TagPrefix;
import mya.mes.mdc.share.vo.plc.PlcTagVo;

import java.io.IOException;
import java.util.List;

public class PlcTagResultJson extends AbstractJsonSerializer<PlcTagResult> {

    @Override
    public void serialize(PlcTagResult value, JsonGenerator gen, SerializerProvider serializers) throws IOException {

        Long objectId = value.objectId;

        gen.writeStartObject();

        serializeData(objectId, value.data, gen, serializers);


        serializeAlarmStart(value.alarmResult, gen, serializers);


        serializeAlarmStop(value.alarmResult, gen, serializers);

        gen.writeEndObject();

    }

    public void serializeData(Long objectId, List<PlcTagVo> data, JsonGenerator gen, SerializerProvider serializers) throws IOException {

        if (data == null || data.isEmpty()) {
            return;
        }
        gen.writeObjectFieldStart("data");

        out(gen, "_id", objectId);

        for (PlcTagVo vo : data) {
            if (TagPrefix.isNumber(vo.dataType)) {
                out(gen, vo.tagName, vo.tagIntValue);
                continue;
            }

            if (TagPrefix.isBoolean(vo.dataType)) {
                out(gen, vo.tagName, vo.tagBoolValue);
                continue;
            }

            if (TagPrefix.isString(vo.dataType)) {
                out(gen, vo.tagName, vo.tagStrValue);
                continue;
            }
        }


        gen.writeEndObject();
    }


    public void serializeAlarmStart(MdcAlarmResult alarmResult, JsonGenerator gen, SerializerProvider serializers) throws IOException {

        if (alarmResult == null || alarmResult.alarmCreatedList == null || alarmResult.alarmCreatedList.isEmpty()) {
            return;
        }
        gen.writeArrayFieldStart("start");

        for (MdcAlarm alarm : alarmResult.alarmCreatedList) {
            serializeAlarm(alarm, gen, serializers);
        }


        gen.writeEndArray();
    }

    public void serializeAlarmStop(MdcAlarmResult alarmResult, JsonGenerator gen, SerializerProvider serializers) throws IOException {

        if (alarmResult == null || alarmResult.alarmCloseList == null || alarmResult.alarmCloseList.isEmpty()) {
            return;
        }
        gen.writeArrayFieldStart("stop");

        for (MdcAlarm alarm : alarmResult.alarmCreatedList) {
            serializeAlarm(alarm, gen, serializers);
        }


        gen.writeEndArray();
    }

    public void serializeAlarm(MdcAlarm alarm, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        if (alarm != null) {
            return;
        }
        gen.writeObject(alarm);
    }


}
